package com.niannian.util;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import com.niannian.R;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

/**
 * amr音频处理
 * 
 */
public class RecordManager {
	private MediaRecorder mMediaRecorder;
	private File file;

	public RecordManager(ImageView view) {

		this.view = view;
	}

	public void setSavePath(File file) {
		this.file = file;
	}

	private long startTime;
	private long endTime;

	/**
	 * 开始录音 使用amr格式
	 * 
	 * @param mRecAudioFile
	 *            录音文件
	 * @return
	 */
	public void startRecord() {
		try {
			stopRecord();
			mMediaRecorder = new MediaRecorder();
			mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
			mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
			mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
			mMediaRecorder.setOutputFile(file.getAbsolutePath());
			mMediaRecorder.prepare();
			mMediaRecorder.start();
			startTime = System.currentTimeMillis();
			if (timeHandler != null) {
				starTimer();
			}

			starShowAnmiTimer();
		} catch (IllegalStateException e) {
		} catch (IOException e) {
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 停止录音
	 * 
	 * @param mMediaRecorder
	 */
	public long stopRecord() {
		try {
			stopTimer();
			sotpShowAnmiTimer();
			if (mMediaRecorder == null)
				return 0L;
			endTime = System.currentTimeMillis();
			mMediaRecorder.stop();
			// mMediaRecorder.reset();
			mMediaRecorder.release();
			mMediaRecorder = null;
			return endTime - startTime;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return 0;
	}

	Boolean isRStatus = false;

	public void setIsRStatus(Boolean isRStatus) {
		this.isRStatus = isRStatus;

	}

	private final Handler showAnmiHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				updateMicStatus();
				break;
			case 2:
				stopRecord();
				break;
			}
			super.handleMessage(msg);
		};
	};
	private int BASE = 600;
	private int SPACE = 100;// 间隔取样时间
	private ImageView view;

	private void updateMicStatus() {
		if (mMediaRecorder != null && view != null) {
			int ratio = mMediaRecorder.getMaxAmplitude() / BASE;

			System.out.println("ratio：" + ratio + "     ");
			int db = 0;// 分贝
			if (ratio > 1)
				db = (int) (20 * Math.log10(ratio));
			System.out.println("分贝值：" + db + "     " + Math.log10(ratio));
			switch (db / 4) {
			case 0:
				view.setImageResource(R.drawable.volume_0);
				break;
			case 1:
				view.setImageResource(R.drawable.volume_1);
				break;
			case 2:
				view.setImageResource(R.drawable.volume_2);
				break;
			case 3:
				view.setImageResource(R.drawable.volume_3);
				break;
			case 4:
				view.setImageResource(R.drawable.volume_4);
				break;
			case 5:
				view.setImageResource(R.drawable.volume_5);
				break;
			case 6:
				view.setImageResource(R.drawable.volume_6);
				break;
			case 7:
				view.setImageResource(R.drawable.volume_7);
				break;

			default:
				view.setImageResource(R.drawable.volume_0);
				break;
			}

		}
	}

	// 动画计时器
	Timer showAnmiTimer;
	TimerTask showAnmiTask;

	/**
	 * 开始动画计时器
	 */
	private void starShowAnmiTimer() {
		if (showAnmiTimer == null) {
			showAnmiTimer = new Timer(true);
		}
		if (showAnmiTask == null) {
			showAnmiTask = new TimerTask() {
				public void run() {
					Message message = new Message();
					if (isRStatus) {
						message.what = 1;
					} else {
						message.what = 2;
					}
					showAnmiHandler.sendMessage(message);
				}
			};
		}
		try {
			showAnmiTimer.schedule(showAnmiTask, 0, SPACE);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 停止动画计时器
	 */
	private void sotpShowAnmiTimer() {
		if (showAnmiTimer != null) {
			showAnmiTimer.cancel();
			showAnmiTimer = null;
		}
		if (showAnmiTask != null) {
			showAnmiTask.cancel();
			showAnmiTask = null;
		}
	}

	// 录音时间记录
	Handler timeHandler;
	Timer timer;
	TimerTask task;

	public void listenerTime(Handler timeHandler) {
		this.timeHandler = timeHandler;
	}

	/**
	 * 计时器
	 */
	private void starTimer() {
		if (timer == null) {
			timer = new Timer(true);
		}
		if (task == null) {
			task = new TimerTask() {
				public void run() {
					Message message = new Message();
					message.what = 1;
					timeHandler.sendMessage(message);
				}
			};
		}
		try {
			timer.schedule(task, 1000, 1000); // 延时1000ms后执行，1000ms执行一次
		} catch (Exception e) {
		}

	}

	private void stopTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (task != null) {
			task.cancel();
			task = null;
		}
	}

}